<template>
  <div class="record-services">
    <header class="mb-8">
      <h1 class="glow-text">记录服务</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <div class="relative">
          <input
            type="text"
            class="input pr-10"
            placeholder="搜索服务..."
            v-model="searchQuery"
          />
          <svg class="w-5 h-5 absolute right-3 top-2.5 text-light-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>

        <div class="ml-4">
          <select class="input bg-dark-darker" v-model="statusFilter">
            <option value="all">所有状态</option>
            <option value="active">活跃</option>
            <option value="inactive">非活跃</option>
          </select>
        </div>
      </div>

      <div class="flex space-x-2">
        <button @click="showCreateModal = true" class="btn btn-primary">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
          </svg>
          添加服务
        </button>
        <button @click="fetchServices" class="btn btn-outline">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          刷新
        </button>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="filteredServices.length === 0" class="text-center py-12 text-light-dark">
      暂无记录服务，请添加记录服务
    </div>

    <div v-else class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr class="border-b border-dark-light">
            <th class="py-3 px-4 text-left">服务名称</th>
            <th class="py-3 px-4 text-left">IP 地址</th>
            <th class="py-3 px-4 text-left">端口</th>
            <th class="py-3 px-4 text-left">状态</th>
            <th class="py-3 px-4 text-left">创建时间</th>
            <th class="py-3 px-4 text-left">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="service in filteredServices"
            :key="service._id"
            class="border-b border-dark-light hover:bg-dark-darker"
          >
            <td class="py-3 px-4">{{ service.service_name }}</td>
            <td class="py-3 px-4 font-mono">{{ service.service_ip }}</td>
            <td class="py-3 px-4">{{ service.service_port }}</td>
            <td class="py-3 px-4">
              <span :class="{
                'badge badge-blue': service.is_active,
                'badge badge-yellow': !service.is_active
              }">{{ service.is_active ? '活跃' : '非活跃' }}</span>
            </td>
            <td class="py-3 px-4 text-light-dark">{{ formatTime(service.created_at) }}</td>
            <td class="py-3 px-4">
              <button
                @click="editService(service)"
                class="text-primary hover:text-primary-light mr-2"
                title="编辑"
              >
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                </svg>
              </button>
              <button
                @click="deleteService(service._id)"
                class="text-accent-pink hover:text-accent-pink/80"
                title="删除"
              >
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="flex justify-between items-center mt-6">
        <div class="text-light-dark">
          共 {{ pagination.total }} 条记录，第 {{ pagination.page }} / {{ pagination.pages }} 页
        </div>
        <div class="flex space-x-2">
          <button
            @click="changePage(pagination.page - 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page <= 1"
          >
            上一页
          </button>
          <button
            @click="changePage(pagination.page + 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page >= pagination.pages"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑服务弹窗 -->
    <div v-if="showCreateModal || showEditModal" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-lg cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">{{ showEditModal ? '编辑服务' : '添加服务' }}</h2>
            <button @click="closeModal" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-4">
            <label class="block text-light-dark mb-2">服务名称</label>
            <input
              v-model="serviceForm.service_name"
              type="text"
              class="input w-full"
              placeholder="例如: user-service"
            />
          </div>

          <div class="mb-4">
            <label class="block text-light-dark mb-2">IP 地址</label>
            <input
              v-model="serviceForm.service_ip"
              type="text"
              class="input w-full"
              placeholder="例如: 10.0.0.1"
            />
          </div>

          <div class="mb-4">
            <label class="block text-light-dark mb-2">端口</label>
            <input
              v-model.number="serviceForm.service_port"
              type="number"
              class="input w-full"
              placeholder="例如: 8080"
              min="1"
              max="65535"
            />
          </div>

          <div class="mb-6">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="serviceForm.is_active"
                class="mr-2"
              />
              <span>活跃状态</span>
            </label>
          </div>

          <div class="flex justify-end">
            <button @click="closeModal" class="btn btn-outline mr-2">取消</button>
            <button @click="saveService" class="btn btn-primary" :disabled="saving">
              <span v-if="saving">保存中...</span>
              <span v-else>保存</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { recordApi } from '../../api';

// 状态变量
const loading = ref(false);
const saving = ref(false);
const showCreateModal = ref(false);
const showEditModal = ref(false);
const searchQuery = ref('');
const statusFilter = ref('all');

// 服务列表
const services = ref<any[]>([]);

// 分页
const pagination = ref({
  page: 1,
  page_size: 10,
  total: 0,
  pages: 1
});

// 服务表单
const serviceForm = ref({
  _id: '',
  service_name: '',
  service_ip: '',
  service_port: 8080,
  is_active: true
});

// 过滤服务
const filteredServices = computed(() => {
  let result = services.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(service =>
      service.service_name.toLowerCase().includes(query) ||
      service.service_ip.includes(query) ||
      service.service_port.toString().includes(query)
    );
  }

  // 状态过滤
  if (statusFilter.value !== 'all') {
    const isActive = statusFilter.value === 'active';
    result = result.filter(service => service.is_active === isActive);
  }

  return result;
});

// 获取服务列表
const fetchServices = async () => {
  try {
    loading.value = true;
    const response = await recordApi.getServices({
      page: pagination.value.page,
      page_size: pagination.value.page_size
    });
    
    if (response && typeof response === 'object') {
      if (Array.isArray(response.services)) {
        services.value = response.services;
      }
      
      pagination.value = {
        page: response.page || 1,
        page_size: response.page_size || 10,
        total: response.total || 0,
        pages: response.pages || 1
      };
    } else {
      // 模拟数据
      services.value = [
        {
          _id: '1',
          service_name: 'user-service',
          service_ip: '10.0.0.1',
          service_port: 8080,
          is_active: true,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        },
        {
          _id: '2',
          service_name: 'order-service',
          service_ip: '10.0.0.2',
          service_port: 8081,
          is_active: true,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        },
        {
          _id: '3',
          service_name: 'payment-service',
          service_ip: '10.0.0.3',
          service_port: 8082,
          is_active: false,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }
      ];
      
      pagination.value = {
        page: 1,
        page_size: 10,
        total: services.value.length,
        pages: 1
      };
    }
  } catch (error) {
    console.error('获取服务列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > pagination.value.pages) return;
  pagination.value.page = page;
  fetchServices();
};

// 编辑服务
const editService = (service: any) => {
  serviceForm.value = {
    _id: service._id,
    service_name: service.service_name,
    service_ip: service.service_ip,
    service_port: service.service_port,
    is_active: service.is_active
  };
  showEditModal.value = true;
};

// 删除服务
const deleteService = async (id: string) => {
  if (!confirm('确定要删除该服务吗？此操作不可恢复。')) return;

  try {
    await recordApi.deleteService(id);
    fetchServices();
  } catch (error: any) {
    console.error('删除服务失败:', error);
    alert(`删除服务失败: ${error.response?.data?.error || error.message}`);
  }
};

// 保存服务
const saveService = async () => {
  // 验证表单
  if (!serviceForm.value.service_name) {
    alert('请输入服务名称');
    return;
  }
  if (!serviceForm.value.service_ip) {
    alert('请输入IP地址');
    return;
  }
  if (!serviceForm.value.service_port || serviceForm.value.service_port < 1 || serviceForm.value.service_port > 65535) {
    alert('请输入有效的端口号(1-65535)');
    return;
  }

  try {
    saving.value = true;
    
    if (showEditModal.value) {
      // 更新服务
      await recordApi.updateService(serviceForm.value._id, {
        service_name: serviceForm.value.service_name,
        service_ip: serviceForm.value.service_ip,
        service_port: serviceForm.value.service_port,
        is_active: serviceForm.value.is_active
      });
    } else {
      // 创建服务
      await recordApi.createService({
        service_name: serviceForm.value.service_name,
        service_ip: serviceForm.value.service_ip,
        service_port: serviceForm.value.service_port,
        is_active: serviceForm.value.is_active
      });
    }
    
    closeModal();
    fetchServices();
  } catch (error: any) {
    console.error('保存服务失败:', error);
    alert(`保存服务失败: ${error.response?.data?.error || error.message}`);
  } finally {
    saving.value = false;
  }
};

// 关闭弹窗
const closeModal = () => {
  showCreateModal.value = false;
  showEditModal.value = false;
  serviceForm.value = {
    _id: '',
    service_name: '',
    service_ip: '',
    service_port: 8080,
    is_active: true
  };
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 生命周期钩子
onMounted(() => {
  fetchServices();
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
